package xiyili;

import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;

import xiyili.compat.Env;

public class G {
        /// for layout params
    public final static int WRAP_CONTENT = ViewGroup.LayoutParams.WRAP_CONTENT;
    public final static int MATCH_PARENT = ViewGroup.LayoutParams.MATCH_PARENT;
	public static final int NETTYPE_WIFI = 0x01;
	public static final int NETTYPE_CMWAP = 0x02;
	public static final int NETTYPE_CMNET = 0x03;

    /**
     * Thus on a 160dpi screen
     * this density value will be 1
     */
    public static  float density;

        /**
     * The absolute width of the display in pixels.
     */
    public static int widthPixels;
    /**
     * The absolute height of the display in pixels.
     */
    public static int heightPixels;

     /**
     * The screen density expressed as dots-per-inch.  May be either
     * {@link android.util.DisplayMetrics#DENSITY_LOW},
      * {@link android.util.DisplayMetrics#DENSITY_MEDIUM}, or
      * {@link android.util.DisplayMetrics#DENSITY_TV}, or
      * {@link android.util.DisplayMetrics#DENSITY_HIGH}, or
      * {@link android.util.DisplayMetrics#DENSITY_400}, or
      * {@link android.util.DisplayMetrics#DENSITY_XHIGH}, or
      * {@link android.util.DisplayMetrics#DENSITY_XXHIGH}, or
      * {@link android.util.DisplayMetrics#DENSITY_XXXHIGH}.
     */
    public static int densityDpi;
    /**
     * A scaling factor for fonts displayed on the display.  This is the same
     * as {@link #density}, except that it may be adjusted in smaller
     * increments at runtime based on a user preference for the font size.
     */
    public static float scaledDensity;
    /**
     * The exact physical pixels per inch of the screen in the X dimension.
     */
    public static float xdpi;
    /**
     * The exact physical pixels per inch of the screen in the Y dimension.
     */
    public static float ydpi;

    public static DisplayMetrics metrics;
    private static Context sContext;

	private G() {

	}

    public static Context ctx() {
        if (sContext == null) {
            throw new IllegalStateException("ApplicationContext was null in G");
        }
        return sContext;
    }

    public static Context ctxOrNull() {
        return sContext;
    }

    public static void init(Context context) {
        sContext = context;
        Resources r = context.getResources();
        DisplayMetrics m  = r.getDisplayMetrics();
        density = m.density;
        densityDpi = m.densityDpi;
        xdpi = m.xdpi;
        ydpi = m.ydpi;
        widthPixels = m.widthPixels;
        heightPixels = m.heightPixels;
        metrics = m;
    }

    ///////////////////////////////////////////////////////////////////////////////
    //////////// 屏幕,尺寸等
    ///////////////////////////////////////////////////////////////////////////////

    /**
     * 将dp转成px
     * @param dp  dips
     * @return px
     */
    public static int dp2px(int dp) {
        return (int) (dp * density + 0.5f);
    }



    /**
     * 获得某一个尺寸资源的像素值
     * @param resId dimen 资源id
     * @return 像素
     */
    public static int pxOf(int resId) {
        return ctx().getResources().getDimensionPixelSize(resId);
    }

    /**
	 * 判断网络是否可用。
	 * 
	 * @return
	 */
	public static boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) ctx()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if ((networkInfo == null) || !networkInfo.isConnectedOrConnecting()) {
			return false;

		}
		return true;
	}

	public static boolean isWifi() {
		return getNetworkType() == NETTYPE_WIFI;
	}

    public static boolean isWifiOr3G() {
        int type = getNetworkType();
        return (type == NETTYPE_WIFI || type == NETTYPE_CMNET);
    }

	/**
	 * 获取当前网络类型
	 * @return 0：没有网络   1：WIFI网络   2：WAP网络    3：NET网络
	 */
	public static int getNetworkType() {
		int netType = 0;
		ConnectivityManager connectivityManager = (ConnectivityManager) ctx().getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return netType;
		}		
		int nType = networkInfo.getType();
		if (nType == ConnectivityManager.TYPE_MOBILE) {
			String extraInfo = networkInfo.getExtraInfo();
			if(!TextUtils.isEmpty(extraInfo)){
				if (extraInfo.toLowerCase().equals("cmnet")) {
					netType = NETTYPE_CMNET;
				} else {
					netType = NETTYPE_CMWAP;
				}
			}
		} else if (nType == ConnectivityManager.TYPE_WIFI) {
			netType = NETTYPE_WIFI;
		}
		return netType;
	}


    /////////////////////////////////////
    //////////  系统服务, 输入法相关,通知,闹钟,钤声
    /////////////////////////////

    public static InputMethodManager inputManager() {
        return (InputMethodManager) ctx().getSystemService(Context.INPUT_METHOD_SERVICE);
    }

    public static WallpaperManager wallpaperManager() {
        return WallpaperManager.getInstance(ctx());
    }

    /**
     * 显示输入法
     */
    public static void showSoftInput() {
        inputManager().toggleSoftInput(2, 0);
    }


    public static NotificationManager notificationManager() {
        return (NotificationManager) ctx().getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public static AlarmManager alarmManager() {
        return (AlarmManager) ctx().getSystemService(Context.ALARM_SERVICE);

    }

    /**
     * 播放通知提示声
     */
    public static void playNotifyRingtone() {
        Ringtone ringtone = RingtoneManager.getRingtone(ctx(),
                RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        if (ringtone != null) {
            ringtone.play();
        }else{
            Log.e("playNotifyRingtone", "NO NOTIFICATION RINGTONE FOUND");
        }
    }

    /**
     * 有可能返回null
     * @param window
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public static void useWallpagerAsWindowBg(Window window) {
        /**
         * 05-09 11:00:51.913    1765-1765/com.xiyili.youjia I/dalvikvm﹕ [ 05-09 11:00:51.913  1765: 1765 D/skia     ]
    --- decoder->decode returned false
05-09 11:00:51.923    1765-1765/com.xiyili.youjia W/WallpaperManager﹕ Can't decode stream
    java.lang.OutOfMemoryError
            at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
            at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:500)
            at android.app.WallpaperManager$Globals.getDefaultWallpaperLocked(WallpaperManager.java:306)
            at android.app.WallpaperManager$Globals.peekWallpaperBitmap(WallpaperManager.java:250)
            at android.app.WallpaperManager.getFastDrawable(WallpaperManager.java:406)
            at xiyili.G.useWallpagerAsWindowBg(G.java:222)

         */
        // 直接使用上面的getFastDrawble等可能造成在小内在的机器上的OOM
        Drawable drawable = null;
        if (Env.hasKitKat) {
            drawable = G.wallpaperManager().getBuiltInDrawable(widthPixels,heightPixels,true,0f,0.5f);
        }else{
            drawable = G.wallpaperManager().getFastDrawable();
        }
        if (drawable != null) {
            window.setBackgroundDrawable(drawable);
        }

    }

    /**
     * 启用全屏
     * @param window
     */
    public static void enableFullscreen(Window window) {
         window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                 WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     *  windowSoftInputMode设置为STATE_VISIBLE ,ADJUST_PAN
     * @param window Window
     */
    public static void enableSoftInput(Window window) {
         window.setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE
                |WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public static void toggleVideoFullScreen(Window window, boolean fullscreen) {
        // Your code to handle the full-screen change, for example showing and hiding the title bar. Example:
        if (fullscreen) {
            WindowManager.LayoutParams attrs = window.getAttributes();
            attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            attrs.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
            window.setAttributes(attrs);
            if (Build.VERSION.SDK_INT >= 14) {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
            }
        } else {
            WindowManager.LayoutParams attrs = window.getAttributes();
            attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
            attrs.flags &= ~WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
            window.setAttributes(attrs);
            if (Build.VERSION.SDK_INT >= 14) {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
            }
        }
    }

    public static void stopVideo(WebView webView) {
        try {
            Class.forName("android.webkit.WebView")
                    .getMethod("onPause", (Class[]) null)
                                .invoke(webView, (Object[]) null);

        } catch(Exception cnfe) {

        }

    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @return
     */
    public static float px2sp(float pxValue) {
        return pxValue / scaledDensity + 0.5f;
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static float sp2px(float spValue) {
        return spValue * scaledDensity + 0.5f;
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static int sp2px(int spValue) {
        return (int) (spValue * scaledDensity + 0.5f);
    }
    ////////////////////////////////


}
